import MarkdownIt, { Token } from 'markdown-it'
import MarkdownItContainer from 'markdown-it-container'
import { toAbsolutePath } from './vueDocGenerator'

export function parseVueDoc(md: MarkdownIt) {
  md.use(MarkdownItContainer, 'VueDoc', {
    validate: function (params: string) {
      return params.trim().match(/^VueDoc\s+(.*)$/)
    },
    render: function (tokens: Token[], idx: number) {
      const m = tokens[idx].info.trim().match(/^VueDoc\s+(.*)$/)

      if (tokens[idx].nesting === 1) {
        // opening tag
        const fileRelativePath = m[1]
        const absPath = toAbsolutePath(fileRelativePath)
        return `<VueDoc vueFileAbsolutePath='${absPath}'>\n`
      } else {
        // closing tag
        return '</VueDoc>\n'
      }
    },
  })
}
